<template>
  <el-form :model="form" :rules="rules" ref="formRef" label-width="100px" class="register-form">
    <div class="overlay"></div>
    <el-row class="form-container">
      <h2>注册</h2>

      <el-input v-model="form.username" placeholder="请输入用户名" required name="username" style="margin-top: 20px;"></el-input>
      
      <el-input v-model="form.account" placeholder="请输入账号" required name="account" style="margin-top: 20px;"></el-input>

      <el-input v-model="form.phone" placeholder="请输入手机号" required name="phone" style="margin-top: 20px;"></el-input>

      <el-input v-model="form.password" type="password" placeholder="请输入密码" required name="password" style="margin-top: 20px;"></el-input>

      <el-input v-model="form.confirmPassword" type="password" placeholder="确认密码" required name="confirmPassword" style="margin-top: 20px;"></el-input>

      <el-form-item class="button-container">
        <el-button type="primary" @click="handleSubmit" style="background: #67a521; ">注册</el-button>
      </el-form-item>

      <div class="footer">
        <p>已有账号？<router-link to="/" style="color: white;">登录</router-link></p>
      </div>
    </el-row>
  </el-form>
</template>

<script>
import instance from "../api/server";

export default {
  name: "Register",
  data() {
    return {
      form: {
        username: "",
        account: "",
        password: "",
        phone: "",
        confirmPassword: "",
      },
      rules: {
        username: [{ required: true, message: "请输入用户名", trigger: "blur" }],
        account: [{ required: true, message: "请输入账号", trigger: "blur" }],
        phone: [{ required: true, message: "请输入手机号", trigger: "blur" }],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
        confirmPassword: [
          { required: true, message: "请确认密码", trigger: "blur" },
          { validator: this.validatePasswordMatch, trigger: "blur" },
        ],
      },
    };
  },
  methods: {
    validatePasswordMatch(rule, value, callback) {
      if (value !== this.form.password) {
        callback(new Error("两次密码输入不一致"));
      } else {
        callback();
      }
    },
    handleSubmit() {
      this.$refs.formRef.validate((valid) => {
        if (valid) {
          this.register();
        } else {
          this.$message.error("表单验证失败");
        }
      });
    },
    register() {
      instance
        .post("/api/register", this.form)
        .then((response) => {
          if (!response.data.status) {
            this.$message.success("注册成功");
            this.$router.push("/");
          } else {
            this.$message.error("注册失败");
          }
        })
        .catch((error) => {
          console.error("注册失败", error);
          this.$message.error("注册请求失败");
        });
    },
  },
};
</script>

<style src="../assets/style/Register.css" scoped> </style>
